package packutil;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FileUtil {

	public static boolean fileExists(String path) {
		File f = new File(path);
		return f.exists();
	}

	public static void writeToFile(String path, Iterator<?> iter) {

		FileWriter fstream = null;
		try {
			fstream = new FileWriter(path);
			PrintWriter out = new PrintWriter(fstream);

			while (iter.hasNext()) {
				out.println(iter.next());
			}

			out.flush();

		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (fstream != null) {
					fstream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				// TODO: log error
			}
		}
	}

	public static void writeToFile(String path, String str) {

		FileWriter fstream = null;
		try {
			fstream = new FileWriter(path);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(str);
			out.flush();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (fstream != null) {
					fstream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				// TODO: log error
			}
		}
	}

	public static String readStringFromFile(String path) {

		String retVal = "";

		FileReader fstream = null;
		try {
			fstream = new FileReader(path);
			BufferedReader in = new BufferedReader(fstream);
			while (in.ready()) {
				retVal += in.readLine() + "\n";
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				fstream.close();
			} catch (IOException e) {
				e.printStackTrace();
				// TODO: log error
			}
		}

		// TODO: why not just TRIM() ???
		if (retVal.contains("\n")) {
			retVal = retVal.substring(0, retVal.lastIndexOf("\n"));
		}

		return retVal;
	}

	public static List<String> readStringsFromFile(String path) {

		List<String> lines = new ArrayList<String>();

		FileReader fstream = null;
		try {
			fstream = new FileReader(path);
			BufferedReader in = new BufferedReader(fstream);
			while (in.ready()) {
				lines.add(in.readLine().trim());
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				fstream.close();
			} catch (IOException e) {
				e.printStackTrace();
				// TODO: log error
			}
		}

		return lines;
	}
}
